//
//  SellTickets3.m
//  TestObjc
//
//  Created by wp w on 12-6-13.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "SellTickets3.h"

@implementation SellTickets3

//这个方法初始化了成员变量
//并启动了三个线程，其中前两个线程执行售票方法 run，第三个线程执行用于测试线程之间是否异步执行的asyn方法。 
- (void) ticket:(ViewController*)controller{ 
    tickets = 100; 
    count = 0; 
    
    //新建同步锁
    ticketsCondition = [[NSCondition alloc] init]; 
    
    //启动三个线程
    //将主线程的指针作为参数传递给多线程
    [self performSelectorInBackground:@selector(run:) withObject:controller];
    [self performSelectorInBackground:@selector(run:) withObject:controller];
    [self performSelectorInBackground:@selector(asyn) withObject:nil];
    
    //这句话会导致线程暂停
    //因为是主线程调用的，所以主线程暂停5秒，暂停时表现为界面点击暂时无响应
    //[NSThread sleepForTimeInterval:5]; 
} 

//测试线程之间是否异步执行。 
-(void) asyn{ 
    [NSThread sleepForTimeInterval:0.1]; 
    printf("***********************************\n"); 
} 

- (void)run:(ViewController*)controller{ 
    while (YES) { 
        //上锁 
        [ticketsCondition lock]; 
        if(tickets > 0){ 
            [NSThread sleepForTimeInterval:0.1]; 
            count = 100 - tickets; 
            NSLog(@"SellTickets3:当前票数是:%d,售出:%d,线程名:%@",tickets,count,[[NSThread currentThread] name]); 
            tickets--; 
            
            //多线程编程中普遍遵循一个原则，就是一切与UI相关的操作都有主线程做，子线程只负责事务，数据方面的处理
            //在iPhone中，需要使用performSelectorOnMainThread 委托主线程处理
            [controller performSelectorOnMainThread: @selector(refreshThreadTitle:) withObject:[NSNumber numberWithInt:0] waitUntilDone: NO];
        }else{ 
            [controller performSelectorOnMainThread: @selector(refreshThreadTitle:) withObject:[NSNumber numberWithInt:1] waitUntilDone: NO];
            break; 
        } 
        //解锁 
        [ticketsCondition unlock]; 
    } 
} 

- (void)dealloc { 
    [ticketsCondition release]; 
    [super dealloc]; 
} 


@end
